<template>
  <el-tooltip :popper-class="`z-tooltip ${popperClass}`"
              v-bind="{disabled:!ellipsis,openDelay:1000,enterable:true,...$attrs}"
              v-on="$listeners">
    <slot name="content"
          slot="content"
          v-if="$slots.content">
    </slot>
    <slot></slot>
  </el-tooltip>
</template>

<script>
import { setStyle } from 'element-ui/lib/utils/dom'
import { v4 } from 'uuid'



export default {
  name: 'ZTooltip',
  props: {
    // The number of omitted lines
    line: {
      type: Number,
      default: 1
    },
    popperClass: String,
    toolTipType: String,
    wrap: {
      type: String,
      default: 'break-word'
    }
  },
  data () {
    return {
      ellipsis: false,
      uuid: v4()
    }
  },
  created () {
    this.checkOnlyRootNode()
  },
  computed: {
    node () {
      return this.$slots.default[0].elm
    }
  },
  mounted () {
    this.checkEllipsis()
    this.node.addEventListener('mouseover', this.checkEllipsis, false)
  },
  destroyed () {
    this.node.removeEventListener('mouseover', this.checkEllipsis)
  },
  methods: {
    checkOnlyRootNode () {
      if (!this.$slots.default) {
        // eslint-disable-next-line no-throw-literal
        throw 'Missing root node !'
      }

      if (Array.isArray(this.$slots.default) && this.$slots.default.length !== 1) {
        // eslint-disable-next-line no-throw-literal
        throw 'Only one root node can exist !'
      }
    },
    checkEllipsis () {
      const style = {
        'overflow': 'hidden',
        'display': '-webkit-box',
        '-webkit-box-orient': 'vertical',
        'position': 'relative',
      }
      style['-webkit-line-clamp'] = this.line
      style['word-break'] = this.toolTipType ? 'break-all' : 'keep-all'
      style['overflow-wrap'] = this.wrap
      setStyle(this.node, style)

      const range = document.createRange()
      range.setStart(this.node, 0)
      range.setEnd(this.node, this.node.childNodes.length)
      const rangeHeight = range.getBoundingClientRect().height

      this.ellipsis = Math.floor(rangeHeight) > this.node.offsetHeight

    }
  }
}
</script>
<style lang="scss">
.z-tooltip {
  width: 280px;
}
</style>
